﻿using Leeder.Logger;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using NewAndong.Comm;
using NewAndong.Model;

namespace NewAndong.Handle
{
    public class TcpHandler
    {
        /// <summary>
        /// 日志
        /// </summary>
        private LogOperate LogObj => Log.GetLogger(this.GetType());

        Socket socketServer;
        Encoding encoding = Encoding.UTF8;
        ConcurrentBag<Socket> socketkints = new ConcurrentBag<Socket>();

        private object lockObj = new object();
        public void BroadcastMessageToAllClients(string mesg)
        {
            lock (lockObj)
            {
                // 将要发送的消息转换为字节数组
                byte[] data = Encoding.Default.GetBytes(mesg);

                ConcurrentBag<Socket> sockets = new ConcurrentBag<Socket>();

                // 遍历集合并移除指定元素
                while (!socketkints.IsEmpty && socketkints.TryTake(out var item))
                {
                    try
                    {
                        // 获取远程端点的IP地址
                        EndPoint remoteEndPoint = item.RemoteEndPoint;
                        if (remoteEndPoint != null)
                        {
                            IPAddress remoteIP = ((IPEndPoint)remoteEndPoint).Address;
                            LogObj.Debug(DateTime.Now + "TCP发送信息TO: " + remoteIP.ToString());
                        }
                        item.Send(data);
                        sockets.Add(item);
                    }
                    catch (Exception ex)
                    {
                        LogObj.Error("TCP发送信息异常: " + ex.ToString());
                        //AppendText($"发送异常{ex.Message}", MessageType.Error);
                    }
                }
                socketkints = sockets;
            }
        }

        public void StartServer(string ip, int port)
        {
            //tcp :协议端
            //实例化一个Tcp协议的socket对象
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //给服务器绑定地址与端口
            IPAddress ipaddress = IPAddress.Parse(ip);
            IPEndPoint iPEndPoint = new IPEndPoint(ipaddress, port);
            //把ip与端口绑定在Socket里面
            socketServer.Bind(iPEndPoint);
            //侦听
            socketServer.Listen(100);
            //AppendText("tcp启动", MessageType.Info);
            System.Threading.Tasks.Task.Run(() =>
            {
                while (true)//循环等待客户端连接
                {
                    //会等待客户端的连接,会卡在这里,不往下运行,直到有下一个宽带连接才会继续往下运行
                    //当有客户端连接的时候,会返回客户端连接的对象
                    Socket socketkint = socketServer.Accept();
                    socketkints.Add(socketkint);
                    var json = GetJson();
                    byte[] byteff = encoding.GetBytes(json);
                    socketkint.Send(byteff);
                    // 获取远程端点的IP地址
                    EndPoint remoteEndPoint = socketkint.RemoteEndPoint;
                    if (remoteEndPoint != null)
                    {
                        IPAddress remoteIP = ((IPEndPoint)remoteEndPoint).Address;
                        LogObj.Info("一个客户端建立连接: " + remoteIP.ToString());
                    }                    //AppendText("一个客户端建立连接", MessageType.Info);
                    System.Threading.Tasks.Task.Run(() =>
                    {
                        try
                        {
                            while (true)//循环接收数据
                            {
                                //接受数据
                                byte[] buffer = new byte[1024];
                                //返回接收到的数据大小,接收数据也会卡住,只有接收到数据的时候才会继续往下进行
                                int longth = socketkint.Receive(buffer);
                                if (longth == 0)
                                {
                                    //AppendText("一个客户端断开连接", MessageType.Info);
                                    LogObj.Info("一个客户端断开连接");
                                    return;
                                }
                                //把字符转成字符串
                                string str = encoding.GetString(buffer, 0, longth);
                                LogObj.Debug(DateTime.Now + "TCP接收数据: " + str);
                                if (str == "ping")
                                {
                                    byte[] byteff1 = encoding.GetBytes("pong");
                                    socketkint.Send(byteff1);
                                }
                                //AppendText(str, MessageType.Info);
                            }
                        }
                        catch (Exception ex)
                        {
                            //AppendText("出现异常", MessageType.Error);
                            return;
                        }
                        finally
                        {
                            socketkint.Close();
                        }

                    });
                }
            });
        }

        public void TcpHeartBeat()
        {
            Thread thread = new Thread(() =>
            {
                LogObj.Info("TCP心跳线程");
                while (true)
                {
                    try
                    {
                        BroadcastMessageToAllClients("200");
                    }
                    catch (Exception ex)
                    {
                    }
                    Thread.Sleep(10000);
                }
            }
            );
            thread.IsBackground = true;
            thread.Start();
        }

        public string GetJson()
        {
            SocketResponseModel socketResponseModel = new SocketResponseModel();
            socketResponseModel.Msg = "连接成功";
            socketResponseModel.Status = "0";

            //WmsDataModel wmsDataModel = new WmsDataModel();
            //wmsDataModel.LinkNumber = "12";
            //wmsDataModel.ProjectName = "测试";
            //
            //var data = CommonUtil.ToJson(wmsDataModel);
            //
            //socketResponseModel.Data = data;

            var json = CommonUtil.ToJson(socketResponseModel);
            return json;
        }
    }
}
